package com.dunshan.data.config;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author dunshan
 * @description: 数据源切换
 * @date 2021-08-15 12:46:32
 */
@Log4j2
@Aspect
@Component
public class DataSourceAspect {



    /**
     * 切点: 所有配置 DataSource 注解的方法
     */
    @Pointcut("execution(public * com.dunshan.data.controller..*.*(..))")
    public void controllerAspect() {
    }

    // 请求method前打印内容
    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint) {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取头标示
        String header = request.getHeader(DataSourceNames.DUNSHAN);
        // 打印请求内容
        log.info("===============请求内容===============");
        log.info("请求地址:" + request.getRequestURL().toString());
        log.info("请求方式:" + request.getMethod());
        log.info("请求类方法:" + joinPoint.getSignature());
        log.info("请求类方法参数:" + Arrays.toString(joinPoint.getArgs()));
        log.info("请求类方法头信息:" + header);


        AppContext context = AppContext.getContext();
        String flag = context.getFlag();
        if (StringUtils.isNotEmpty(flag) && flag.equals(DataSourceNames.HEAD)) {
            MDC.put(DataSourceNames.DUNSHAN, DataSourceNames.SHADOW);
            log.info("Mysql Pressure measurement flow");
            DynamicDataSource.setDataSource(DataSourceNames.SHADOW);
        } else {
            MDC.put(DataSourceNames.SHADOW, DataSourceNames.PRODUCE);
            log.info("Mysql Real traffic");
            DynamicDataSource.setDataSource(DataSourceNames.PRODUCE);
        }
    }
}
